package com.javafactroy.kunlong.bip.icp.socket.client;

import com.javafactroy.kunlong.bip.icp.common.config.BipConfig;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;
import com.javafactroy.kunlong.bip.icp.message.dxp.base.DxpHeader;
import com.javafactroy.kunlong.bip.icp.message.dxp.base.DxpMsgResp;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Properties;

/**
 * @author xingzhiwen
 * @date 2021/9/14
 * @ddescription:
 */
@Component
@Slf4j
@Data
public class SocketTcpClient {

    Socket socket;
    @Autowired
    BipConfig bipConfig;

    IMessage recieveReply() throws IOException {

        InputStream inputStream = socket.getInputStream();

        byte[] bytes = new byte[DxpHeader.MSG_HEADER_LEN];
        int readLen = inputStream.read(bytes);
        if (readLen != -1) {
            //根据读取到的长度，显示字符串
            DxpMsgResp message = new DxpMsgResp();
            message.getHeader().decode(bytes);

            log.info("client receive messageRsp message.getHeader(): {}", message.getHeader().getMsgLen());
            ByteBuffer byteBuffer = ByteBuffer.allocate(message.getHeader().getMsgLen());
            byteBuffer.put(bytes);
            byte[] body = new byte[message.getHeader().getMsgLen() - DxpHeader.MSG_HEADER_LEN];
            readLen = inputStream.read(body);
            if (readLen != -1) {
                //根据读取到的长度，显示字符串
                byteBuffer.put(body);
                byteBuffer.rewind();
                message.decode(byteBuffer.array());
                log.info("client receive messageRsp : \n{}", message.toJSONString());
                return message;
            }
        }
        return null;
    }

    void sendRequest(IMessage msg) throws IOException {

        OutputStream outputStream = socket.getOutputStream();

        byte[] bytes = msg.encode();
        log.info("client send request2server:" + new String(bytes,"UTF-8"));
        outputStream.write(bytes);
        //关闭流对象和socket
        //outputStream.close();
    }

    @Autowired
    private Environment env;

    public void setIpPort(String ip, int port) {
        if (bipConfig == null) {
            bipConfig = new BipConfig();
            bipConfig.setProps(new Properties());
        }
        bipConfig.getProps().setProperty("server.ip", ip);
        bipConfig.getProps().setProperty("server.port", String.valueOf(port));
    }

    public void connect() throws IOException {
        String ip = bipConfig.getProps().getProperty("server.ip");
        String port = bipConfig.getProps().getProperty("server.port");

        log.info("客户端socket连接 ip:port={}:{}", ip, port);
        socket = new Socket(ip, Integer.valueOf(port));

    }

    public IMessage send(IMessage msg) throws IOException {
        try {
            connect();
            sendRequest(msg);
            return recieveReply();
        } finally {
            if (socket != null) {
                log.info("客户端结束连接");

                //socket.sendUrgentData();
                socket.shutdownOutput();
                socket.shutdownInput();
                socket.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {


    }
}
